import datetime
from flask import Blueprint, render_template, request, session
from flask_login import login_required, current_user
from sqlalchemy import desc
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Member
from applications.models import Memberrole
from applications.models import Examination

admin_examination = Blueprint('adminExamination', __name__, url_prefix='/admin/examination')


# 用户管理
@admin_examination.get('/')
@authorize("admin:examination:main")
def main():
    return render_template('admin/examination/main.html')


# 表格数据
@admin_examination.get('/data')
@authorize("admin:examination:main")
def table():
    title = str_escape(request.args.get('title', type=str))
    types = str_escape(request.args.get('type', type=int))
    filters = []
    if title:
        filters.append(Examination.title.contains(title))
    if types:
        filters.append(Examination.type.contains(types))
    examination = Examination.query.filter(*filters).layui_paginate()
    return table_api(
        data=[{
            'id': Examination.id,
            'title': Examination.title,
            'user_id': Examination.user_id,
            'username': Examination.username,
            'num': Examination.num,
            'commentnum': Examination.commentnum,
            'create_time': Examination.create_time
        } for Examination in examination.items],
        count=examination.total)


# 增加
@admin_examination.get('/add')
@authorize("admin:examination:add", log=True)
def add():
    return render_template('admin/examination/add.html')


# 添加
@admin_examination.post('/save')
@authorize("admin:examination:add", log=True)
def save():
    req = request.get_json(force=True)
    # memberroleid = req.get("memberroleid")
    # roles= Memberrole.query.filter_by(id=memberroleid).first()
    # name =roles.rolename
    types = str_escape(req.get("type"))
    answers = str_escape(req.get("answer"))
    option = str_escape(req.get("option"))
    title = str_escape(req.get("title"))
    username = "admin"
    user_id = 1
    sort = str_escape(req.get("sort"))
    create_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    role = Examination(
        type=types,
        answers=answers,
        content=option,
        title=title,
        username=username,
        user_id=user_id,
        create_time=create_time,
        sort=sort
    )
    db.session.add(role)
    db.session.commit()
    return success_api(msg="添加成功")


# 编辑
@admin_examination.get('/edit/<int:id>')
@authorize("admin:examination:edit", log=True)
def edit(id):
    i = 0
    strs = []
    answers = 0
    r = get_one_by_id(model=Examination, id=id)
    if r.type == 1 or r.type == 2:
        strs = r.content.split(',')
    if r.type == 1:
        answers = int(r.answers)
    if r.type == 2:
        # answers = []
        answers = r.answers.split(',')
    if r.type == 3:
        answers = int(r.answers)

    data = Examination(
        id=r.id,
        type=r.type,
        content=strs,
        title=r.title,
        answers=answers,
        sort=r.sort
    )
    return render_template('admin/examination/edit.html', member=data)


@admin_examination.post('/update')
@authorize("admin:examination:edit", log=True)
def update():
    reqs = request.get_json(force=True)
    id = reqs.get("memberId")
    if not id:
        return fail_api(msg="数据异常，请联系管理员")
    # memberroleids = reqs.get("memberroleid")
    # roles = Memberrole.query.filter_by(id=memberroleids).first()
    # names = roles.rolename
    types = str_escape(reqs.get("type"))
    answers = str_escape(reqs.get("answer"))
    option = str_escape(reqs.get("option"))
    title = str_escape(reqs.get("title"))
    sort = str_escape(reqs.get("sort"))
    update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    datas = {
        "type": types,
        "answers": answers,
        "content": option,
        "title": title,
        "update_time": update_time,
        "sort": sort
    }
    examination = Examination.query.filter_by(id=id).update(datas)
    db.session.commit()
    if not examination:
        return fail_api(msg="更新角色失败")
    return success_api(msg="更新成功")


# 删除
@admin_examination.delete('/remove/<int:id>')
@authorize("admin:examination:remove", log=True)
def remove(id):
    r = Examination.query.filter_by(id=id).delete()
    db.session.commit()
    if not r:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除
@admin_examination.delete('/batchRemove')
@authorize("admin:examination:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        r = Examination.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")


# 启用
@admin_examination.put('/enable')
@authorize("admin:examination:edit", log=True)
def enable():
    id = request.get_json(force=True).get('Id')
    if id:
        res = enable_status(Member, id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="操作成功")
    return fail_api(msg="数据错误")


# 禁用
@admin_examination.put('/disable')
@authorize("admin:examination:edit", log=True)
def dis_enable():
    _id = request.get_json(force=True).get('Id')
    if _id:
        res = disable_status(Member, _id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="操作成功")
    return fail_api(msg="数据错误")
